package model

import (
	"fmt"
	"ginblog/utils/errmsg"
	"github.com/jinzhu/gorm"
)

type Article struct {
	Category Category `gorm:"foreignkey:Cid"`
	gorm.Model
	Title   string `gorm:"type:varchar(50);not null" json:"title"`
	Cid     int    `gorm:"type:int;not null" json:"cid"`
	Desc    string `gorm:"type:varchar(200);not null" json:"desc"`
	Content string `gorm"type:longtext" json:"content"`
	Img     string `gorm:"type:varchar(500)" json:"img"`
}

//新增article
func AddArticle(data *Article)int {
	err := db.Debug().Create(&data).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

//编辑article
func EditArticle(id int, data *Article) int {
	var article Article
	map1 := make(map[string]interface{})
	map1["title"] = data.Title
	map1["cid"] = data.Cid
	map1["desc"] = data.Desc
	map1["content"] = data.Content
	map1["img"] = data.Img
	err := db.Debug().Model(&article).Where("id = ?", id).Update(map1).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

//删除article
func DeleteArticle(id int) int {
	var article Article
	err := db.Debug().Where("id = ?", id).Delete(&article).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

//查询所有文章
func GetArticles() ([]Article, int) {
	var articles []Article
	err := db.Debug().Find(&articles).Error
	if err != nil {
		return nil, errmsg.ERROR
	}
	return articles, errmsg.SUCCESS
}

//查询单个文章
func GetArticle(id int) (Article, int) {
	var article Article
	err := db.Debug().Where("id = ?", id).First(&article).Error
	if err != nil {
		return article,errmsg.ERROR_ART_NOT_EXIST
	}
	return article, errmsg.SUCCESS
}

//根据分类查询文章
func GetCategoryArticle(cid int, pageSize int, pageNum int)([]Article, int) {
	var articles []Article
	fmt.Println("cid is: ", cid)
	err := db.Debug().Preload("Category").Limit(pageSize).Offset((pageNum - 1)*pageSize).Where("cid = ?", cid).Find(&articles).Error
	if err != nil {
		return articles, errmsg.ERROR_CATE_NOT_EXIST
	}
	return articles, errmsg.SUCCESS

}